package com.journey.org.ui.video.small

import android.annotation.SuppressLint
import android.app.Application
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableInt
import androidx.lifecycle.viewModelScope
import com.journey.org.BR
import com.journey.org.R
import com.journey.org.app.HttpManager
import com.mvvmhabit.org.base.BaseViewModel
import com.mvvmhabit.org.binding.command.BindingAction
import com.mvvmhabit.org.binding.command.BindingCommand
import com.mvvmhabit.org.custom.LoadingLayout
import io.reactivex.disposables.Disposables
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.tatarka.bindingcollectionadapter2.ItemBinding

/**
 * @Date: 2020/11/19 16:52
 * @Author:小妖
 * @Description: 小视频
 */
class SmallVideoViewModel(application: Application) : BaseViewModel(application) {

    val requestStateField = ObservableInt()

    val onClickAgainLoadCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            page = 0
            items.clear()
            loadNeteaseVideoList()
        }
    })

    override fun onCreate() {
        super.onCreate()
        items.clear()
        loadNeteaseVideoList()
    }

    var page = 0

    val onRefreshCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            items.clear()
            page = 0
            loadNeteaseVideoList()
        }
    })

    val onLoadMoreCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            page += 10
            loadNeteaseVideoList()
        }
    })

    val itemBinding =
        ItemBinding.of<SmallVideoItemViewModel>(BR.viewModel, R.layout.small_video_item)

    val items = ObservableArrayList<SmallVideoItemViewModel>()

    @SuppressLint("CheckResult")
    fun loadNeteaseVideoList() {
        viewModelScope.launch(Dispatchers.Main) {
            if (page == 0) {
                requestStateField.set(LoadingLayout.NETWORK_LOADING)
            }
            val entities = withContext(Dispatchers.IO) {
                HttpManager.getInstance().loadNeteaseVideoList("V9LG4CHOR", page)
            }
            if (!entities?.V9LG4CHOR.isNullOrEmpty()) {
                entities?.V9LG4CHOR?.forEach { entity ->
                    items.add(SmallVideoItemViewModel(this@SmallVideoViewModel, entity))
                }
                requestStateField.set(LoadingLayout.HIDE_LAYOUT)
            } else {
                if (page == 0) {
                    requestStateField.set(LoadingLayout.NODATA)
                }
                cancel()
            }
        }
    }
}